id = getQueryVariable("id");
var annexList = [];
(function ($) {
    //默认参数
    var defaluts = {
        searchName: '.ySearchSelect'
    };

    $.fn.extend({
        "ySearchSelect": function (options) {
            defaluts.searchName = options;
            var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆盖插件默认参数
            return this.each(function () {  //这里的this 就是 jQuery对象。这里return 为了支持链式调用
                init(opts);
            });

        }
    });
    //初始化插件
    function init(o){
        $(document).click(function(){
            var thin = this;
            $(".ySearchSelect table").hide();
            $(".ySearchSelect .input-text").hide();
            $(".ySearchSelect .layui-form.layui-border-box.layui-table-view").hide();
            $(".ySearchSelect i.layui-edge").removeClass("select");
        });

        $(o.searchName+" .layui-input").click(function(event){
            //阻止document点击事件
            event.stopPropagation();
            if($(this).siblings(".input-text").length <= 0){
                var str = '<div class="input-text">'+
                    '<input type="text" name="" placeholder="输入关键字" class="layui-input">'+
                    '</div>';
                $(o.searchName).append(str);
            }
            if($(this).siblings("table").css("display") == "none"){
                var ids = $(o.searchName).attr("data-id");
                table.render({
                    elem: '#productcodeselect_'+ids,
                    id: 'productcodeselecttableid_'+ids,
                    data: data3,
                    cols: [[
                        {field: 'productcode', width: 120, title: '产品编码'},
                        {field: 'specificationcoding', width: 120, title: '规格编码'},
                        {field: 'chinesename', width: 120, title: '中文名称'},
                        {field: 'englishnames', width: 120, title: '英文名称'},
                        {field: 'productcatalog', width: 120, title: '产品目录'}
                    ]],
                    height: 200
                });
                table.on('row(productcodeselecttable_'+ids+')', function(obj){
                    var data = obj.data;
                    var tabledata = table.cache["storageproductstableid"];
                    $.each(tabledata,function(index,value){
                        if(value.id==ids){
                            tabledata[index]["productcode"] = data.productcode;
                        }
                    });
                    table.reload('storageproductstableid',{});
                });
                $(this).siblings("i").addClass("select");
                $(this).siblings("table").show();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").show();
                $(this).siblings(".input-text").show();
            }else{
                $(this).siblings("i").removeClass("select");
                $(this).siblings("table").hide();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").hide();
                $(this).siblings(".input-text").hide();
            }
            $(o.searchName+" .input-text input").focus();
            $(o.searchName+" .input-text").width(605);

            //键盘监听事件
            $(o.searchName+" .input-text input").keyup(function(event){
                if(event.keyCode != 38 && event.keyCode != 40 && event.keyCode != 13){
                    ySearchSelectMate($(this).val(),o.searchName);
                }
            });
        });
    }

    //匹配搜索，不匹配则隐藏。
    function ySearchSelectMate(value,name){
        value = $.trim(value.toString()); // 去掉两头空格
        var ids = $(name).attr("data-id");
        //模糊查询表格并刷新
        table.reload('productcodeselecttableid_'+ids,{where: {
                productcode:value
            }});
    }
})(window.jQuery);

var form = layui.form, laydate = layui.laydate, upload = layui.upload, table = layui.table, $ = layui.jquery, id = getQueryVariable("id");
var data0 = [];
var data1 = [];
var data2 = [];
var data3 =[]
lay('.starttime').each(function(){
    laydate.render({
        elem: this,
        type: 'date',
        // showBottom: false,
        done: function(value, date, endDate){
            if(this.elem[0].id == "actualdischargedateatd" || this.elem[0].id == "wldate"){
                if(value!=""){
                    $("."+this.elem[0].id+"text").css("background","#fff");
                }else{
                    $("."+this.elem[0].id+"text").css("background","red");
                }
            }

        }
    });
});
//表单初始值，修改时调用
if (id != "") {
    form.val("editor-form", {
        "invoicenumber": "进入修改",
    })
}
//监听提交
form.on('submit(form-element)', function (data) {
    var indexsl = 0;
    var storageproductsdata = table.cache["storageproductstableid"];
    var costtabledata = table.cache["costtableid"];
    for(let i in costtabledata){
        if(costtabledata[i].costtype!=undefined&&costtabledata[i].costtype!=null&&costtabledata[i].costtype!=""){
            costtabledata[i].typeCode=costtabledata[i].costtype
        }
    }
    var productsatabledata = partList
    if(indexsl == 0){
        //提交表单
        var bill=getBillFrom()
        var clearid="";//清关表单id
        $.ajax({
            url: 'clearChange/insertBillChangeInfo?type=1',
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            async: false, // 同步
            data: JSON.stringify(bill),
            success: function (date) {
                clearid=date.data;
            }
        });
        var products=storageproductsdata;
        var part=partList;
        for (let i in products){
            var product=products[i]//单个产品产品提交
            var bid=product.clearId
            var carryProductsId=product.carryProductsId
            //找出该产品的配件信息
            var thisPart=new Array()
            for(let i in partList){
                if(partList[i].clearId==bid&&partList[i].clearProductId==carryProductsId){
                    thisPart.push(partList[i])
                }
            }
            //提交产品 并返回产品主键
            $.ajax({
                url: 'clearChange/insertBillChangeProductInfo?type=1&clearId='+clearid,
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                async: false, // 同步
                data: JSON.stringify(product),
                success: function (date) {
                    var  productid=date.data;
                    //提交配件
                    $.ajax({
                        url: 'clearChange/insertBillChangePartInfo?type=1&clearId='+clearid+"&productid="+productid,
                        type: 'POST',
                        contentType: "application/json; charset=utf-8",
                        async: false, // 同步
                        data: JSON.stringify(thisPart),
                        success: function (date) {
                        }
                    });
                }
            });
        }
        //提交费用
        $.ajax({
            url: 'clearChange/insertBillChangeCost?type=1&clearId='+clearid,
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            async: false, // 同步
            data: JSON.stringify(costtabledata),
            success: function (date) {
            }
        });
        //提交附件
        //获取头部表单数据
        let req = data.field;
        //获取附件数据
        let annexReqs = table.cache["attachmenttableid"];
        let datas = JSON.stringify(annexReqs);
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:datas,
            url:"clearChange/add?id="+clearid+"&type=-1",
            success:function(res){
                if(res.status == 200){
                    layer.msg("保存成功", {icon: 6});
                    setTimeout(function () {
                        //保存成功则刷新提交过来的界面 并关闭此页面
                        parent.detab("views/jsp/ExportBusiness/billClear.jsp");
                        parent.intab("views/jsp/ExportBusiness/billClear.jsp","清关")
                        parent.detab("views/jsp/ExportBusiness/tpl/billClearChange.jsp"+(id==''?'':'?id='+id));
                    },1000);
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                return false;
            }
        });

    }
    return false;
});

function getBillFrom(){
    var s=0;
    if($("#clear_1").val()=="是"){
        s=1
    }
    var bill={
        "clearId":$("#clearId").val(),
        "customerName": $("input[name='customername']").val(),
        "invoiceDate":$("input[name='idate']").val(),
        "salesmanName":$("input[name='salesman']").val(),
        "shippingDate":$("input[name='shdate']").val(),
        "settleDate":$("input[name='edrdate']").val(),
        "invoiceNo":$("input[name='invoicenumber']").val(),
        "carryInvoiceNo":$("input[name='invoicenumber']").val(),
        "moneyKind": $("input[name='currency']").val(),
        "usdRate":$("input[name='exchangerate']").val(),
        "rmbRate":$("input[name='rmbexchangerate']").val(),
        "startPlace":$("#place").val(),
        "endPlace": $("#destination").val(),
        "settleMode":$("#settlementway").val(),
        "priceTerm":$("#priceterms").val(),
        "invoiceMoney": $("input[name='invoicetotalamount']").val(),
        "contractNo":$("input[name='salescontractno']").val(),
        "custContractNo":$("input[name='customercontractno']").val(),
        "salesman":$("input[name='salesman']").val(),
        "businessMode": $("input[name='businessmodel']").val(),
        "asPerInNo": $("input[name='asperinno']").val(),
        "stock": $("input[name='warehouse']").val(),
        "overdue": $("input[name='withinlimit']").val(),
        "payday": $("input[name='containertype']").val(),
        "companyName":$("#signingcompany").val(),
        "bankName":$("#bank").val(),
        "opname": $("input[name='theoperator']").val(),
        "instockDate":$("input[name='wldate']").val(),
        "actualAtd":$("input[name='actualdischargedateatd']").val(),
        "totalTariffAmount":$("input[name='totaltariffamount']").val(),
        "companyCode":$("#signingcompanyCode").val(),
        "custCode":$("#custCode").val(),
        "opcode":$("#opCode").val(),
        "salesmanCode":$("#salesmanCode").val(),
        "customerLevelName":$("#customerLevelName").val(),
        "clear_1":s,
        "clear_2":$("#clear_2").val()
        // "clearAllPlace":$("#clearAllPlace").val(),
        // "clear_1":$("#clear_1").val(),
        // "clear_2":$("#clear_2").val(),
        // "clear_3":$("#clear_3").val(),
    }
    return bill;

}

$(document).ready(function () {
    firstGet()
    form.render();
    if(id!=''){
        idGet()
    }
    //加载签约公司
    $.ajax({
        url: 'billDeclare/selectAllcompanyAndpeople',
        type: 'GET',
        success: function (date) {
            var map=date.data
            var company=[]
            $.each(map, function (key, value) {
                if(key=="companyName"){
                    company=value
                }
            });
            for(let i in company){
                $("#signingcompany").append("<option value='"+company[i].name+"'>"+company[i].name+"</option>")
            }
            form.render();
        }
    });
})

var bill=''
function idGet() {
    getInfo()
    table.reload('storageproductstableid',{
        data:productslist
    })
    showInfo()
}
function  showInfo() {
    var info=bill[0]
    $("input[name='customername']").val(info.customerName);
    $("input[name='idate']").val(info.invoiceDate);
    $("input[name='shdate']").val(info.shippingDate);
    $("input[name='edrdate']").val(info.settleDate);
    $("input[name='invoicenumber']").val(info.invoiceNo);
    $("input[name='currency']").val(info.moneyKind);
    $("input[name='exchangerate']").val(info.usdRate);
    $("input[name='rmbexchangerate']").val(info.rmbRate);
    $("#place").find("option[value='"+info.startPlace+"']").attr("selected",true);
    $("#destination").find("option[value='"+info.endPlace+"']").attr("selected",true);
    $("#settlementway").find("option[value='"+info.settleMode+"']").attr("selected",true);
    $("#priceterms").find("option[value='"+info.priceTerm+"']").attr("selected",true);
    $("input[name='invoicetotalamount']").val(info.invoiceMoney);
    $("input[name='salescontractno']").val(info.contractNo);
    $("input[name='customercontractno']").val(info.custContractNo);
    $("input[name='salesman']").val(info.salesman);
    $("input[name='businessmodel']").val(info.businessMode);
    $("input[name='asperinno']").val(info.asPerInNo);
    $("input[name='warehouse']").val(info.stock);
    $("input[name='withinlimit']").val(info.overdue);
    $("input[name='containertype']").val(info.payday);
    $("#signingcompany").find("option[value='"+info.companyName+"']").attr("selected",true);
    $("#signingcompanyCode").val(info.companyCode);
    $("#bank").find("option[value='"+info.bankName+"']").attr("selected",true);
    $("input[name='theoperator']").val(info.opname);
    $("input[name='totaltariffamount']").val(info.totalTariffAmount);
    $("input[name='actualdischargedateatd']").val(info.actualAtd);
    $("input[name='wldate']").val(info.instockDate);
    $("input[name='createdate']").val(info.createTime);
    // $("input[name='clearAllPlace']").val(info.clearAllPlace);
    // $("input[name='clear_1']").val(info.clear_1);
    // $("input[name='clear_2']").val(info.clear_2);
    // $("input[name='clear_3']").val(info.clear_3);
    var s="否"
    if(first.clear_1==1){
        s="是"
    }
    $("#clear_1").val(s);
    $("#clear_2").val(first.clear_2);
    form.render();
}
function getInfo(){
    $.ajax({
        url: 'clearChange/selectInfoBillById?clearId='+id,
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            var map=date.data;
            $.each(map, function (key, value) {
                if(key=="clear"){
                    bill=value
                }
                if(key=="products"){
                    productslist=value
                }
                if(key=="parts"){
                    partList=value
                }
            });
        }
    });
}

function firstGet() {
    getPriceTerm()
    getsettleMode()
    getstartplace()
    getendplace()
    getbank()
}
function   getCost(){
    var  cost1= getdictionary(5,19)
    var cost=new Array();
    for(let i in cost1){
        cost.push(cost1[i])
    }
    return cost

}
function  getPriceTerm(){
    var  PriceTerm= getdictionary(5,16)
    for(let i in PriceTerm){
        $("#priceterms").append("  <option value='"+PriceTerm[i].name+"'>"+PriceTerm[i].name+"</option>")
    }
}
function  getsettleMode(){
    var  PriceTerm= getdictionary(5,18)
    for(let i in PriceTerm){
        $("#settlementway").append("  <option value='"+PriceTerm[i].name+"'>"+PriceTerm[i].name+"</option>")
    }
}
function  getstartplace(){
    var  PriceTerm= getdictionary(6,31)
    for(let i in PriceTerm){
        $("#place").append("  <option value='"+PriceTerm[i].name+"'>"+PriceTerm[i].name+"</option>")
    }
}
function   getendplace(){
    var  PriceTerm= getdictionary(6,31)
    for(let i in PriceTerm){
        $("#destination").append("  <option value='"+PriceTerm[i].name+"'>"+PriceTerm[i].name+"</option>")
    }
}
function   getbank(){
    var  PriceTerm= getdictionary(6,32)
    for(let i in PriceTerm){
        $("#bank").append("  <option value='"+PriceTerm[i].name+"'>"+PriceTerm[i].name+"</option>")
    }
}

function getdictionary(dl,xl) {
    var obj=[];
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data: {"type":dl,"lx":xl},
        url:'dictionary2/getValues',
        dataType:"json",
        // contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                obj=da.data;
                hs=obj;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return obj;
}
var productslist=[]
var list=[]
//--产品信息
var tariffMoney=new Map();
table.render({
    elem: '#storageproducts',
    id: 'storageproductstableid',
    data: list,
    toolbar: '#storageproductstoolbar',
    cols: [[
        {checkbox: true, fixed: true},
        {field: 'saleContractNo', width: 120, title: '外销合同号'},

        {field: 'goodsCode', width: 220, title: '产品编码'},
        {field: 'specCode', width: 120, title: '规格编码'},
        {field: 'specNo', width: 120, title: '规格说明'},
        {field: 'goodsCname', width: 120, title: '中文名称'},
        {field: 'goodsEname', width: 120, title: '英文名称'},
        {field: 'goodsCdesc', width: 120, title: '中文描述'},
        {field: 'goodsEdesc', width: 120, title: '英文描述'},
        {field: 'goodsNum', width: 80, title: '产品数量'},
        {field: 'mastAmount', width: 120, title: '剩余数量', templet: function(element){
                var  ftotalprice=element.lastAmount;
                if(id!=-1){
                    $.ajax({
                        url: 'clearChange/selectLastAmontById?proid='+element.carryProductsId+'&type=1',
                        type: 'GET',
                        async: false, // 同步
                        success: function (date) {
                            ftotalprice=date.data;
                        }
                    });
                }
                return ftotalprice;
            }},
        {field: 'lastAmount', width: 140, title: '本次清关数量',edit:'text'},
        {field: 'clearOnePlace', width: 140, title: '清关单价',edit:'text'},
        {field: 'clearAllPlace', width: 140, title: '清关总价',edit:'text'},
        {field: 'goodsUnit', width: 120, title: '单位'},
        {field: 'funitprice', width: 80, title: '单价',edit:'text'},
        {field: 'ftotalprice', width: 120, title: '金额小计'},
        {field:'tariffRate', title:'关税税率', width: 120 , templet: function(element){

                var tar= getProductHscode(element.goodsCode,element.specCode);
                return tar;
            }},
        {field:'tariffMoney', title:'关税金额', width: 120, templet: function(element){
                var price= $("#priceterms").val();
                var tariffRate= getProductHscode(element.goodsCode,element.specCode);
                var tari=0;
                if(price.substring(0,3)=='DDP'){
                    tari=element.costSubtotal*1.2*tariffRate*0.01
                }else if(price.substring(0,3)=='EXW'){
                    tari=element.costSubtotal*1.2*tariffRate*0.01

                }
                tari = Math.floor(tari * 100) / 100;
                var  id=element.carryProductsId;
                var  tars1=tari;
                tariffMoney.set(id,tars1);
                var tars=0;
                tariffMoney.forEach(function (value,key) {
                    tars+=value;
                })
                tars = Math.floor(tars * 100) / 100;
                $("#tars").val(tars);
                form.render()
                return tari;
            }},
        {field: 'color', width: 120, title: '颜色'},
        {field: 'goodsGross', width: 120, title: '毛重',edit:'text'},
        {field: 'totalGross', width: 120, title: '毛重小计'},
        {field: 'netweight', width: 120, title: '净重',edit:'text'},
        {field: 'totalNet', width: 120, title: '净重小计'},
        {field: 'bulk', width: 120, title: '体积',edit:'text'},
        {field: 'totalBulk', width: 120, title: '体积小计'},
        {field: 'totalTray', width: 120, title: '托数'},
        {field: 'trayNum', width: 120, title: '每托量',edit:'text'},
        {field: 'piecesNum', width: 120, title: '件数'},
        {field: 'perpiecesNum', width: 120, title: '每件数量',edit:'text'},
        {field: 'paymentpaymentdays', width: 120, title: '付款账期',edit:'text'},
        {field: 'finishedProductCost', width: 120, title: '成品成本',edit:'text'},
        {field: 'accessoriesCost', width: 120, title: '配件成本',edit:'text'},
        {field: 'supplyerName', width: 120, title: '供应商',edit:'text'},
        {field: 'stockNo', width: 120, title: '采购单号'},
        {field: 'costUnitPrice', width: 80, title: '成本单价',edit:'text'},
        {field: 'costSubtotal', width: 120, title: '成本小计', templet: function(element){
                var price=element.costUnitPrice;
                return Math.floor(price*element.lastAmount * 100) / 100;

            }},

        {fixed: 'right', title: '操作', width: 120, align: 'center', toolbar: '#storageproductseditor'}]],
    page: true,
    limit:20,
    height: 380
    , done: function (res, curr, count) {
        $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
        $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
        for(var i = 0;i<res.data.length;i++){
            var product=res.data[i]
            if(productslist.length==0){
                productslist.push(res.data[i])
            }else{
                ispro=0;//判断重复
                for(let i in productslist){
                    if(product.clearId==productslist[i].clearId&&product.carryProductsId==productslist[i].carryProductsId){
                        ispro=1;//重复
                    }
                }
                if(ispro==0){
                    productslist.push(res.data[i])
                }
            }

            var clearId =res.data[i].clearId;//未提交前临时存放出运明细表id
            var carryProductsId=res.data[i].carryProductsId;//出运产品id
            $.ajax({
                url: 'clearChange/selectAllPart?carryid='+clearId+'&carryproid='+carryProductsId,
                type: 'GET',
                success: function (date) {
                    var parts=date.data
                    for(let i in parts){
                        var part=parts[i]
                        var istrue=0;//判断是否重复
                        if(partList.length==0){
                            partList.push(parts[i]);
                        }else{
                            for(let i in partList){
                                if(part.clearId==partList[i].clearId&&part.clearProductId==partList[i].clearProductId&&part.carryPartsId==partList[i].carryPartsId){
                                    istrue=1;//重复
                                }
                            }
                            if(istrue==0){
                                partList.push(parts[i]);
                            }}
                    }
                }
            });
        }
        invoicetotalamount();
    }
});
function  getProductHscode(goodsCode,specCode) {
    var tar=0
    var hgCode=''
    $.ajax({
        url: 'clearChange/selectTariffRate?goodsCode='+goodsCode+'&specCode='+specCode,
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            hgCode=date.data;
        }
    })
    var hs=getdictionary(3,8);
    for(let i in hs){
        if(hs[i].code==hgCode){
            tar=hs[i].importTariff
        }
    }
    return tar;
}

//保留两位小数
function toDecimal(x) {
                var f = parseFloat(x);
                if (isNaN(f)) {
                     return;
                    }
                f = Math.round(x*100)/100;
                return f;
 }
form.on("select(grossweightselect_filter)", function(data){
    var elem = data.othis.parents("tr");
    var dataindex = elem.attr("data-index");
    var tabledata = table.cache["storageproductstableid"];
    $.each(tabledata,function(index,value){
        if(value.LAY_TABLE_INDEX==dataindex){
            tabledata[index]["grossweight"] = data.value;
        }
    });
});
form.on("select(customscodeselect_filter)", function(data){
    var elem = data.othis.parents("tr");
    var dataindex = elem.attr("data-index");
    var tabledata = table.cache["storageproductstableid"];
    $.each(tabledata,function(index,value){
        if(value.LAY_TABLE_INDEX==dataindex){
            tabledata[index]["customscode"] = data.value;
        }
    });
});
form.on("select(unitselect_filter)", function(data){
    var elem = data.othis.parents("tr");
    var dataindex = elem.attr("data-index");
    var tabledata = table.cache["storageproductstableid"];
    $.each(tabledata,function(index,value){
        if(value.LAY_TABLE_INDEX==dataindex){
            tabledata[index]["unit"] = data.value;
        }
    });
});
//修改产品
table.on('edit(storageproductstable)',function (obj) {
    var declare=obj.data //得到当前行数据
    var old = $(this).prev().text();//旧值
    if(obj.field=="lastAmount"){
        var newInt=parseFloat(obj.value)
        var oldInt=parseFloat(old)
        if(id!=-1){
            $.ajax({
                url: 'clearChange/selectLastAmontById?proid='+declare.carryProductsId+'&type=1',
                type: 'GET',
                async: false, // 同步
                success: function (date) {
                    oldInt=date.data;
                }
            });
        }
        if(newInt>oldInt){
            // layer.msg('数量超过可清关数量，请重新输入');
            // $(this).val(old);
            // return;
        }else  if(newInt<0){
            layer.msg('数量不能为负，请重新输入');
            $(this).val(old);
            return;
        }else{
            declare.ftotalprice=toDecimal(newInt*declare.funitprice) //修改金额小计
            var chengben=toDecimal(newInt*declare.costUnitPrice)
            declare.costSubtotal=chengben//成本小计
            // var price= $("#priceterms").val();
            // var tari=0;
            // // if(price.substring(0,3)=='DDP'){
            // //    var tariffRate= getProductHscode(declare.goodsCode,declare.specCode);
            // //     tari=chengben*1.2*tariffRate*0.01
            // // }else if(price.substring(0,3)=='EXW'){
            // //     var tariffRate= getProductHscode(declare.goodsCode,declare.specCode);
            // //     tari=chengben*1.2*tariffRate*0.01
            // //
            // // }
            // declare.tariffMoney=tari//关税总额
            declare.totalTray=toDecimal(newInt/declare.trayNum)//托数
            var newNum= toDecimal(newInt/declare.perpiecesNum)
            declare.piecesNum=newNum//件数
            declare.totalGross=toDecimal(newNum*declare.goodsGross)//毛重小计
            declare.totalNet=toDecimal(newNum*declare.netweight)//净重小计
            declare.totalBulk=toDecimal(newNum*declare.bulk)//体积小计
            obj.update(declare) //修改当前行数据
            obj.update(declare) //修改当前行数据
            for(let i in partList){
                if(partList[i].clearProductId==declare.carryProductsId){
                    if(partList[i].cpbl!=null&&partList[i].cpbl!=""&&partList[i].pebl!=null&&partList[i].pebl!=""){
                        partList[i].lastAmount=(newInt/partList[i].cpbl)*partList[i].pebl
                    }else{
                        partList[i].lastAmount=newInt
                    }
                    partList[i].costSubtotal=toDecimal(partList[i].costUnitPrice*partList[i].lastAmount);
                }
            }
            table.reload('productsatableid', {})
        }

    }
    //修改其他数据
    if(obj.field=="goodsGross"){
        var newInt=parseFloat(obj.value)
        declare.totalGross=toDecimal(newInt*declare.piecesNum)//毛重小计
        obj.update(declare) //修改当前行数据
    }
    if(obj.field=="netweight"){
        var newInt=parseFloat(obj.value)
        declare.totalNet=toDecimal(newInt*declare.piecesNum)//净重小计
        obj.update(declare) //修改当前行数据
    }
    if(obj.field=="bulk"){
        var newInt=parseFloat(obj.value)
        declare.totalBulk=toDecimal(newInt*declare.piecesNum)//体积小计
        obj.update(declare) //修改当前行数据
    }
    if(obj.field=="trayNum"){
        var newInt=parseFloat(obj.value)
        declare.totalTray=toDecimal(declare.lastAmount/newInt)//托数
        obj.update(declare) //修改当前行数据
    }
    if(obj.field=="perpiecesNum"){//修改每件件数
        var newInt=parseFloat(obj.value)
        var newNum= toDecimal(declare.lastAmount/newInt)//件数
        declare.piecesNum=newNum
        declare.totalGross=toDecimal(newNum*declare.goodsGross)//毛重小计
        declare.totalNet=toDecimal(newNum*declare.netweight)//净重小计
        declare.totalBulk=toDecimal(newNum*declare.bulk)//体积小计
        obj.update(declare) //修改当前行数据
    }
    if(obj.field=="costUnitPrice"){//修改成本
        var newInt=parseFloat(obj.value)
        var chengben=toDecimal(newInt*declare.lastAmount)
        declare.costSubtotal=chengben//成本小计
        // var price= $("#priceterms").val();
        // var tari=0;
        // if(price.substring(0,3)=='DDP'){
        //     var tariffRate= getProductHscode(declare.goodsCode,declare.specCode);
        //     tari=chengben*1.2*tariffRate*0.01
        // }else if(price.substring(0,3)=='EXW'){
        //     var tariffRate= getProductHscode(declare.goodsCode,declare.specCode);
        //     tari=chengben*1.2*tariffRate*0.01
        // }
        // declare.tariffMoney=tari//关税总额
        obj.update(declare) //修改当前行数据
    }
    if(obj.field=="funitprice"){//修改金额小计
        var newInt=parseFloat(obj.value)
        declare.ftotalprice=toDecimal(declare.lastAmount*newInt)
        obj.update(declare) //修改当前行数据
    }
    invoicetotalamount();
    //判断数据类型 ,,,,,,,
    if((obj.field== "number" || obj.field== "unitprice"|| obj.field== "amountsubtotal"|| obj.field== "volume" || obj.field== "joenumber" || obj.field== "quantityeachhold"|| obj.field== "costunitprice" || obj.field== "costsubtotal" || obj.field== "finishedproductcost" || obj.field== "sparepartscost")&&!isNumber(obj.value)) {
        layer.msg('请输入数字');
        $(this).val(old);
        return;
    }
});

var partList=[]
//监听行单击事件
table.on('row(storageproductstable)', function(obj){

    var carryid= obj.data.clearId//出运明细id  或清关表id
    var carryproid=obj.data.carryProductsId  //出运产品id
    var showPart=[]
    for(let i in partList){
        if(partList[i].clearId==carryid&&partList[i].clearProductId==carryproid){
            showPart.push(partList[i])
        }
    }
    $("#hidden").show();
    table.render({
        elem: '#productsaselect'
        ,data:showPart
        ,toolbar: '#productsatoolbar'
        ,where:{id:obj.data.id} //查询的产品ID，条件
        ,cols: [[
            {checkbox: true, fixed: true}
            ,{field: 'goodsCode', title: '产品编码', width: 220}
            ,{field: 'specCode', title: '规格编码'}
            ,{field:'cpbl', title:'成品比例', edit:'text'}
            ,{field:'pebl', title:'配件比例', edit:'text'}
            ,{field:'goodsnumParts', title:'配件数量', edit:'text'}
            ,{field: 'mastAmount', width: 120, title: '剩余数量', templet: function(element){
                    var  ftotalprice=element.lastAmount;
                    if(id!=-1){
                        $.ajax({
                            url: 'clearChange/selectLastAmontById?proid='+element.carryPartsId+'&type=2',
                            type: 'GET',
                            async: false, // 同步
                            success: function (date) {
                                ftotalprice=date.data;
                            }
                        });
                    }
                    return ftotalprice;
                }}
            ,{field:'lastAmount', title:'本次清关数量',width: 140, edit:'text'}
            ,{field: 'costUnitPrice', width: 120, title: '成本单价', edit:'text'}
            ,{field: 'costSubtotal', width: 120, title: '成本小计',edit:'text'}
            ,{field: 'stockNo', width: 120, title: '采购单号',edit:'text'}
            ,{field: 'supplyerName', width: 120, title: '供应商',edit:'text'}
            ,{field:'goodsCname', title:'中文名称',edit:'text'}
            ,{field:'goodsEname', title:'英文名称',edit:'text'}
            ,{field:'goodsGross', title:'毛重' ,edit:'text'}
            ,{field:'netWeight', title:'净重', edit:'text'}
            ,{field:'bulk', title:'体积' ,edit:'text'}
        ]]
        ,id: 'productsatableid'
        // ,page: true
            ,limit:50
        ,height:300
    });
});
table.on('edit(productsatable)',function (obj) {//修改配件
    var declare=obj.data //得到当前行数据
    var old = $(this).prev().text();//旧值
    if(obj.field=="lastAmount"){
        var newInt=parseInt(obj.value)
        var oldInt=parseInt(old)
        if(id!=-1){
            $.ajax({
                url: 'clearChange/selectLastAmontById?proid='+declare.carryPartsId+'&type=2',
                type: 'GET',
                async: false, // 同步
                success: function (date) {
                    oldInt=date.data;
                }
            });
        }
        if(newInt>oldInt){
            layer.msg('数量超过可报关数量，请重新输入');
            $(this).val(old);
            return;
        }else  if(newInt<0){
            layer.msg('数量不能为负，请重新输入');
            $(this).val(old);
            return;
        }else{
            declare.costSubtotal=declare.costUnitPrice*newInt
            obj.update(declare) //修改当前行数据
        }

    }
    if(obj.field=="costUnitPrice"){//修改成本
        var newInt=parseFloat(obj.value)
        declare.costSubtotal=toDecimal(declare.lastAmount*newInt)
        obj.update(declare) //修改当前行数据
    }

    //判断数据类型 ,,,,,,,
    if((obj.field== "finishedproductratio" || obj.field== "accessoriesproportion"|| obj.field== "number"|| obj.field== "costprice" || obj.field== "costsubtotal" || obj.field== "expressaddress" || obj.field== "netweight" ||obj.field== "volume")&&!isNumber(obj.value)) {
        layer.msg('请输入数字');
        $(this).val(old);
        return;
    }
    for(let i in partList){
        if(declare.clearId==partList[i].clearId&&declare.clearProductId==partList[i].clearProductId&&declare.carryPartsId==partList[i].carryPartsId){
            partList[i]=declare;
        }
    }

});

table.on('tool(storageproductstable)', function (obj) {
    if (obj.event === 'del') {
        layer.confirm('真的删除行么', function (index) {
            //需要删除的ID：data.id
            var partTemp=new Array();
            for(let i in partList){
                if(obj.data.clearId!=partList[i].clearId||obj.data.carryProductsId!=partList[i].clearProductId){
                    partTemp.push(partList[i])
                }
            }
            var proTemp=new Array();
            for(let i in productslist){
                if(productslist[i].carryProductsId!=obj.data.carryProductsId){
                    proTemp.push(productslist[i])
                }
            }
            productslist=proTemp
            partList=partTemp
            obj.del();
            table.reload('productsatableid', {})
            layer.msg("删除成功", {icon: 6});
            invoicetotalamount()
            layer.close(index);
            //修改销售合同号
            updateSalescontractno()
        });

    }

});

table.on('toolbar(storageproductstable)', function (obj) {
    var checkStatus = table.checkStatus(obj.config.id);
    switch (obj.event) {
        case 'importshipmentdetailsjh':
            layer.open({
                type: 2,
                area: $(window).width() < 458 ? "['100%', '100%']":['95%', '95%'],
                content: 'views/jsp/ExportBusiness/tpl/billClearImport.jsp',
                end:function () {
                    form.render()
                }
            });
            break;
        case 'new':
            var oldData = table.cache["storageproductstableid"];
            var data1={"id":oldData.length+1,warehousename:"",number:"",unitprice:"",amountsubtotal:"",costprice:"",costsubtotal:"",productcode:""};
            oldData.push(data1);
            table.reload('storageproductstableid',{data : oldData});
            break;
        case 'del':
            var data=checkStatus.data
            if(data!=""){
                layer.confirm('确定删除所选项吗？',function (index) {
                    //删除配件
                    var partTemp=new Array();
                    for(let i in partList){
                        var part=partList[i]
                        var  products= checkStatus.data
                        var istrue=0;//用来判断配件属于删除的产品
                        for(let i in products){
                            if(part.clearId==products[i].clearId&&part.clearProductId==products[i].carryProductsId){
                                istrue=1;//确认属于
                            }
                        }
                        if(istrue!=1){
                            partTemp.push(part);
                        }
                    }
                    partList=partTemp
                    table.reload('productsatableid', {data:[]})
                    var  products= checkStatus.data
                    var productTemp=new Array();
                    for(let i in productslist){
                        var product=productslist[i]
                        var products= checkStatus.data
                        var istrue=0;//用来判断产品属于删除的产品
                        for(let i in products){
                            if(product.clearId==products[i].clearId&&product.carryProductsId==products[i].carryProductsId){
                                istrue=1;//确认属于
                            }
                        }
                        if(istrue!=1){
                            productTemp.push(product);
                        }
                    }
                    productslist=productTemp
                    table.reload("storageproductstableid", {
                        data: productslist,
                    });
                    layer.msg('删除成功');
                    //修改销售合同号
                    updateSalescontractno()
                })
            }else{
                layer.msg('请选择需要删除的行');
            }

            break;
    };

});
//修改销售合同号
function  updateSalescontractno() {
    var produces = table.cache["storageproductstableid"];
    var sale=new Map()
    var cust=new Map()
    for(let i in produces){
        if(produces[i].saleContractNo!=null&&produces[i].saleContractNo!=""){
            sale.set(produces[i].saleContractNo,1);
        }
        if(produces[i].clientContractNo!=null&&produces[i].clientContractNo!=""){
            cust.set(produces[i].clientContractNo,2)
        }
    }
    var customerContractNo=""
    cust.forEach(function(value,key){
        customerContractNo+=key+"-"
    });
    var salesContractNo="";
    sale.forEach(function(value,key){
        salesContractNo+=key+"-"
    });
    if(customerContractNo=="null-"&&salesContractNo!=null){
        customerContractNo=salesContractNo
    }
    if(salesContractNo=="null-"&&customerContractNo!=null){
        salesContractNo=customerContractNo
    }
    $("input[name='salescontractno']").val(salesContractNo.substr(0,salesContractNo.length-1));
    $("input[name='customercontractno']").val(customerContractNo.substr(0,customerContractNo.length-1));
}

function hoverOpenImg() {
    var img_show = null; // tips提示
    $("body").delegate("td img", "mouseover", function () {
        var img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
        img_show = layer.tips(img, this, {
            tips: [2, 'rgba(41,41,41,.5)']
            , area: ['160px']
        });
    });
    $("body").delegate("td img", "mouseout", function () {
        layer.close(img_show);
    });
}



//---费用
table.render({
    elem: '#cost'
    , data: []
    , toolbar: '#costtoolbar'
    , cols: [[
        {checkbox: true, fixed: true}
        , {field: 'typeName', title: '费用类型',templet:"#costtypeselect"}
        , {field: 'amount', title: '金额',event:'amount',edit:'text'}
        , {field: 'memo', title: '备注说明',edit:'text'}
        , {field: 'contractNo', title: '外销合同号',edit:'text'}
    ]]
    , id: 'costtableid'
    , height: 380
    , page: true
    ,limit:20
    , done: function (res, curr, count) {
        $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
        $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
        var cost= getCost();
        for(let i in cost){
            $(".costType").append(new Option(cost[i].name,cost[i].code));
        }
        for (var i = 0; i < res.data.length; i++) {
            $('.costType:eq('+i+') option[value="'+res.data[i].typeCode+'"]').prop("selected",true);
        }
        form.render('select');
    }
});
table.on('edit(costtable)',function (obj) {
    var old=$(this).prev().text();//旧值
    //判断数据类型 ,,,,,,,
    if(obj.field== "amount"){
        invoicetotalamount()
    }
});
form.on("select(costtypeselect_filter)", function(data){
    var elem = data.othis.parents("tr");
    var dataindex = elem.attr("data-index");
    var tabledata = table.cache["costtableid"];
    $.each(tabledata,function(index,value){
        if(value.LAY_TABLE_INDEX==dataindex){
            tabledata[index]["costtype"] = data.value;
        }
    });
});

table.on('toolbar(costtable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    var data = checkStatus.data;
    switch(obj.event){
        case 'new':
            var oldData = table.cache["costtableid"];
            var data1={"id":oldData.length+1,costtype:"",amount:"",descr:""};
            oldData.push(data1);
            table.reload('costtableid',{data : oldData});
            break;
        case 'del':
            var data=checkStatus.data,delList=[];
            data.forEach(function(n,i){
                delList.push(n.id);
            });
            if(delList!=''){
                layer.confirm('确定删除所选项吗？',function (index) {
                    var cbList = table.cache["costtableid"];
                    for(var i = 0;i<cbList.length;i++){
                        delList.forEach((item, index) => {
                            //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                            if (typeof (cbList[i]) != "undefined"&&item == cbList[i].id) {
                                cbList.splice(i, 1);
                            }
                        })
                    }
                    table.reload("costtableid", {
                        data: cbList,
                    });
                    layer.msg('删除成功');
                    invoicetotalamount()
                })

            }else{
                layer.msg('请选择需要删除的行');
            }
            break;
    };
});


//---附件
table.render({
    elem: '#attachment'
    , data: annexList
    , toolbar: '#attachmenttoolbar'
    , cols: [[
        {field: 'fileName', title: '文件名', fixed: true}
        , {field: 'uploadTime', title: '上传日期', fixed: true}
        , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
    ]]
    , id: 'attachmenttableid'
    , height: 380
    , page: true
    ,limit:50
});
upload.render({
    elem: '#uploadfile'
    , url: 'clearChange/uploadFile'
    , field: "uploadify"
    , accept: 'file'
    , multiple: true
    , auto: false
    , bindAction: '#testListAction'
    , choose: function (obj) {
        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
        //读取本地文件
        obj.preview(function (index, file, result) {
            var tr = $(['<tr id="upload-' + index + '">'
                , '<td>' + file.name + '</td>'
                , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                , '<td>等待上传</td>'
                , '<td>'
                , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                , '</td>'
                , '</tr>'].join(''));

            //单个重传
            tr.find('.demo-reload').on('click', function () {
                obj.upload(index, file);
            });

            //删除
            tr.find('.demo-delete').on('click', function () {
                delete files[index]; //删除对应的文件
                tr.remove();
                uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
            });

            $("#uploadlist").append(tr);
        });
    }
    , parseData: function(res){
        return {
            "code": res.status,
            "count": res.total,
            "data": res.data
        };
    }
    , done: function (res, index, upload) {
        let data = res.data;
        for(var i in data){
            if (data[i].status) { //上传成功
                annexList.push(data[i]);
                var tr = $("#uploadlist").find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            this.error(index, upload);
        }
    }
    , error: function (index, upload) {
        var tr = $("#uploadlist").find('tr#upload-' + index)
            , tds = tr.children();
        tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
    }
});

table.on('toolbar(attachmenttable)', function (obj) {
    switch (obj.event) {
        case 'uploadfile':
            $("#uploadlist").html(""); //清空上传列表数据
            layer.open({
                type: 1,
                title: "文件上传",
                area: ['710px', '340px'],
                content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                , cancel: function (index, layero) {
                    table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                }
            });
            break;
    }
    ;
});
table.on('tool(attachmenttable)', function (obj) {
    let data = obj.data;
    if (obj.event === 'download') { //下载
        let xmlHttpRequest = new XMLHttpRequest();
        let url = "wjinfo/downloadfile2?filename=" + data.filePath;
        xmlHttpRequest.open('GET', url, true);
        //设置请求头
        xmlHttpRequest.setRequestHeader("Content-type", "application/json")
        xmlHttpRequest.responseType = "blob";
        xmlHttpRequest.send(null);

        xmlHttpRequest.onload = function() {
            let content = xmlHttpRequest.response;
            // 组装a标签
            let elink = document.createElement("a");

            //设置文件下载路径
            elink.download = decodeURIComponent(data.fileName);
            elink.style.display = "none";
            let blob = new Blob([content], { type: 'application/force-download' });

            //解决下载不存在文件的问题，根据blob大小判断
            if(blob.size==0){
                layer.msg('服务器没找到此文件，请联系管理员!');
            }else{
                elink.href = window.URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                document.body.removeChild(elink);
            }

        }
    } else if (obj.event === 'del') {
        layer.confirm('确认删除?', function (index) {
            obj.del();
            let id = data.id;
            for (var i = 0; i < annexList.length; i++) {
                if (annexList[i].id == id) {
                    annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                    i--; // 如果不减，将漏掉一个元素
                    break;
                }
            }
            layer.msg("删除成功", {icon: 6});
            layer.close(index);
            table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
        });
    }
});

//发票总额 productslist   partList   var costtabledata = table.cache["costtableid"];
function invoicetotalamount() {
    var invoicetotalamount=0;
    var products = table.cache["storageproductstableid"];
    for(let i in products){
        if(products[i].ftotalprice!=""&&products[i].ftotalprice!=null){
            invoicetotalamount+=products[i].ftotalprice;
        }
    }
    var costtabledata = table.cache["costtableid"];
    for(let i in costtabledata){
        if(costtabledata[i].amount!=""&&costtabledata[i].amount!=null){
            invoicetotalamount+=parseFloat(costtabledata[i].amount);
        }
    }
    $("input[name='invoicetotalamount']").val(toDecimal(invoicetotalamount));
}
form.on('select(priceterms)', function(data){
    table.reload('storageproductstableid',{});
});
//---操作日志
table.render({
    elem: '#otherwarehouselog'
    , data: data2
    , cols: [[
        {field: 'operationtype', title: '操作类型', fixed: true}
        , {field: 'theoperator', title: '操作员'}
        , {field: 'operationdate', title: '操作日期'}
        , {field: 'modifythecontent', title: '修改内容'}
    ]]
    , id: 'logtableid'
    , height: 380
    , limit: 30//显示的数量
    , page: true
    ,limit:50
});
//验证单号是否唯一
function checkBillNo() {
    var invoicenumber = $("input[name='invoicenumber']").val()
    $.ajax({
        url: 'clearChange/checkBillNo?invoicenumber=' + invoicenumber + "&id=" + id,
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            if (date.data == "wrong") {
                $("input[name='invoicenumber']").val("")
                layer.msg("清关发票号已存在,请重新输入")
            }

        }
    });
}